package parser;

import config.BeanDefinition;
import config.BeanProperty;
import config.MutablePropertyValues;
import exceptions.BeanCreationException;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import registry.BeanDefinitionRegistry;
import registry.SimpleBeanDefinitionRegistry;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlBeanDefinitionReader implements BeanDefinitionReader{

    private BeanDefinitionRegistry beanDefinitionRegistry;

    public XmlBeanDefinitionReader(){
        this.beanDefinitionRegistry = new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return beanDefinitionRegistry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        if(configLocation == null || "".equals(configLocation.trim()))
            return;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(configLocation);

        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();

        for(Element element: elements){
            //取出id属性和class属性
            String id = element.attributeValue("id");
            String clazz = element.attributeValue("class");

            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(clazz);

            //取出property标签
            List<Element> propertyElements = element.elements("property");
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            for(Element propertyElement : propertyElements){
                //取出name属性和ref属性
                String name = propertyElement.attributeValue("name");
                String ref = propertyElement.attributeValue("ref");
                mutablePropertyValues.addBeanProperty(new BeanProperty(name,ref));
            }
            beanDefinition.setMutablePropertyValues(mutablePropertyValues);
            beanDefinitionRegistry.registerBeanDefinition(id,beanDefinition);
        }

    }
}
